package com.richie696.catalina;

import java.util.LinkedHashMap;
import java.util.Map;

public class StandardWrapper implements Wrapper {

    private String warAbstractPath;
    private String name;
    private final Map<String, ServletMapping> mappings = new LinkedHashMap<>(10);
    private WebAppClassLoader webAppClassLoader;

    @Override
    public String getWarAbstractPath() {
        return warAbstractPath;
    }

    @Override
    public void setWarAbstractPath(String warAbstractPath) {
        this.warAbstractPath = warAbstractPath;
        setWebAppClassLoader();
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public WebAppClassLoader getWebAppClassLoader() {
        return webAppClassLoader;
    }

    public void setWebAppClassLoader() {
        this.webAppClassLoader = new WebAppClassLoader(warAbstractPath);
    }

    @Override
    public ServletMapping getServletMapping(String servletName) {
        return this.mappings.get(servletName);
    }

    @Override
    public void addServletMapping(String servletName, ServletMapping servletMapping) {
        this.mappings.put(servletName, servletMapping);
    }

    @Override
    public ServletMapping getServletMappingByUrl(String url) {
        for (Map.Entry<String, ServletMapping> en : mappings.entrySet()) {
            ServletMapping mapping = en.getValue();
            for (String urlPattern : mapping.getUrlPatterns()) {
                if (("/" + url).matches(urlPattern)) {
                    return mapping;
                }
            }
        }
        return null;
    }

}
